<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/18
 * Time: 21:03
 */
namespace Admin\Controller;
use Think\Controller;
class PayController extends Controller {

    public function ttt(){
        $order=M('shop_transactions_record','','XYC')->where(['order_num'=>'WCZ20181105113433','status'=>3])->find();

        $q=intval($order['money']*100);
        if($q=='996'){
            echo $q;
        }else{
            echo 1;
        }

    }

    public function notify()
    {
        //接收回调信息
        $res=file_get_contents('php://input');
        // $result = $_POST;
        //存日志里
        file_put_contents('./Public/log/jd_active_notify.log', date('Y-m-d H:i:s').'成功回调' . file_get_contents('php://input') . "\n", FILE_APPEND);
        // file_put_contents('./Public/log/jd_active_notify.log', date('Y-m-d H:i:s').'成功回调' .json_encode($_POST). "\n", FILE_APPEND);
        //对回调信息格式进行解析
        parse_str($res,$parr);
        $result = $parr;
        //*****************
        //进行相关业务处理        
        
        if($result['trade_status']=='FINI' && $result['is_success']=='Y'){

            $order_number = $result['out_trade_no'];
            $money = $result['trade_amount']/100;
            $merchant=M('merchant','','XYC');
            $balance_record=M('balance_record','','XYC');
            $vz_loan=M('vz_loan','','XYC');
            $user = M('user','','XYC');
            
            $merchant->startTrans();
            $balance_record->startTrans();
            $vz_loan->startTrans(); 
            $user->startTrans(); 

            $user_id = M('vz_loan','','XYC')->where(array('order_number'=>$order_number))->getField('user_id');
            $shop_identifier = M('user','','XYC')->where(array('id'=>$user_id))->getField('shop_identifier');
            $ret1=M('merchant','','XYC')->where(['shop_identifier'=>$shop_identifier])->setDec('withhold_balance',$money);

            $ret2=$balance_record->add(['shop_identifier'=>$shop_identifier,'money'=>$money,'detail'=>'代扣打款','type'=>1,'ctime'=>time(),'cost_type'=>3]);

            $ret3 = $vz_loan->where(array('order_number'=>$order_number))->save(array('is_success'=>2,'get_time'=>time(),'status'=>1));

//            $ret4 = M('user','','XYC')->where(array('id'=>$user_id))->setDec('quota',$money);
            if($ret1 && $ret2 && $ret3){

                add_control_log($shop_identifier,$shop_identifier,$order_number.'【代扣】打款'.$money.'元',3);

                //每一笔代扣消费要记录
//                if($shop_identifier=='0100010030'){
                    $service_cost= M('merchant','','XYC')->where(['shop_identifier'=>$shop_identifier])->getfield('withhold_service_money');
                    M('merchant','','XYC')->where(['shop_identifier'=>$shop_identifier])->setDec('withhold_balance',$service_cost);
                    M('balance_record','','XYC')->add(['shop_identifier'=>$shop_identifier,'mobile'=>$user_id,'cost_type'=>4,'ctime'=>time(),'detail'=>'代扣打款服务费','type'=>1,'money'=>$service_cost]);
//                }

                $merchant->commit();
                $balance_record->commit();
                $vz_loan->commit();                
                $user->commit();
                echo 'success';die;
            }else{
                
                $merchant->rollback();
                $balance_record->rollback();
                $vz_loan->rollback();
                $user->rollback();
                echo 'fail';die;
            }
            echo 'success';
        }else{
            echo "fail";die;
        }
        //*****************

    }

    /**
     *支付回响
     */
    public function echo_pay(){
        echo '支付成功';
    }
    
    /**
     * 京东充值支付回调业务逻辑
     */
    public function jd_notify(){
        $url='https://pay.dstlkj.com/External/external_decrypt_notify';
        $arr_p= file_get_contents('php://input');
        $arr=['data'=>$arr_p];
        $result=http($url,$arr,1);
//        file_put_contents('./Public/log/jd_active_notify.log',date('Y-m-d H:i:s').'-*****-'.$arr_p.'-**-'."\n",FILE_APPEND);
        file_put_contents('./Public/log/jd_active_notify.log',date('Y-m-d H:i:s').'-*****-'.$result.'-**-'."\n",FILE_APPEND);
        $data=json_decode($result,true);

        $shop=M('shop_transactions_record','','XYC');
        $merchant=M('merchant','','XYC');
        $balance_record=M('balance_record','','XYC');
        $shop->startTrans();
        $merchant->startTrans();
        $balance_record->startTrans();

        $respose=$data['code'];
        $order_unm=$respose['tradeNum'];
        if($respose['status']=='2'){
         $order=M('shop_transactions_record','','XYC')->where(['order_num'=>$order_unm,'status'=>3])->find();
         if(intval($order['money']*100)==$respose['amount']){
             $update= M('shop_transactions_record','','XYC')->where(['order_num'=>$order_unm,'status'=>3])->setField('status',1);
             $update1=$merchant->where(['shop_identifier'=>$order['shop_identifier']])->setInc('withhold_balance',$order['discount_money']);
             $ret2=$balance_record->add(['shop_identifier'=>$order['shop_identifier'],'mobile'=>$order['mobile'],'money'=>$order['money'],'detail'=>'商户后台-代扣充值','type'=>2,'ctime'=>time(),'cost_type'=>4]);
             if($update && $update1 && $ret2){

                 add_control_log($order['shop_identifier'],$order['operator'],'【商户后台-代扣充值】充值'.$order['money'].'元',3);
                 $shop->commit();
                 $merchant->commit();
                 $balance_record->commit();
                 echo 'success';die;
             }else{
                 $shop->rollback();
                 $merchant->rollback();
                 $balance_record->rollback();
                 echo 'fail';die;
             }

         }else{
             echo 'fail';die;
         }

        }else{
            echo 'fail';die;
        }
    }

    /**
     * 支付宝支付通知功能
     */
    public function notify_ali(){
        $arr=$_POST;
        file_put_contents('./Public/log/alipay.log',date('Y-m-d H:i:s').'--'.json_encode($arr),FILE_APPEND);
        $config = C('ALI_CONFIG');
        Vendor('Alipay.pagepay.service.AlipayTradeService');
        $alipaySevice = new \AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST,true));
        $result = $alipaySevice->check($arr);
        /** 实际验证过程建议商户添加以下校验。
         * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
         * 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
         * 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
         * 4、验证app_id是否为该商户本身。
         */
        if($result) {//验证成功
        //商户订单号
        $out_trade_no = $_POST['out_trade_no'];
        //支付宝交易号
        $trade_no = $_POST['trade_no'];
        //交易状态
        $trade_status = $_POST['trade_status'];
        if($_POST['trade_status'] == 'TRADE_FINISHED') {
            //判断该笔订单是否在商户网站中已经做过处理
            //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
            //如果有做过处理，不执行商户的业务程序
            //注意：
            //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
        }
        else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
            $shop=M('shop_transactions_record','','XYC');
            $merchant=M('merchant','','XYC');
            $balance_record=M('balance_record','','XYC');
            $shop->startTrans();
            $merchant->startTrans();
            $balance_record->startTrans();
            $record=M('shop_transactions_record','','XYC')->where(['order_num'=>$out_trade_no])->find();
            if($record['money']==$_POST['total_amount']){
                $ret=M('shop_transactions_record','','XYC')->where(['order_num'=>$out_trade_no])->setField('status',1);
                if($record['type']==1){//1短信充值2认证充值5代扣充值
                    $type='商户后台-短信充值';
                    $ret1=M('merchant','','XYC')->where(['shop_identifier'=>$record['shop_identifier']])->setInc('msg_balance',$record['money']);
                }elseif($record['type']==2){//1短信充值2认证充值5代扣充值
                    $type='商户后台-认证充值';
                    $ret1=M('merchant','','XYC')->where(['shop_identifier'=>$record['shop_identifier']])->setInc('aut_balance',$record['money']);
                }else{
                    $type='商户后台-代扣充值';
                    $ret1=M('merchant','','XYC')->where(['shop_identifier'=>$record['shop_identifier']])->setInc('withhold_balance',$record['money']);
                }
                $ret2=$balance_record->add(['shop_identifier'=>$record['shop_identifier'],'mobile'=>$record['mobile'],'money'=>$record['money'],'detail'=>$type,'type'=>2,'ctime'=>time(),'cost_type'=>$record['type']]);
                if(!empty($ret) && !empty($ret1) &&!empty($ret2)){
                    add_control_log($record['shop_identifier'],$record['operator'],'【'.$type.'】充值'.$record['money'].'元',3);
                    $shop->commit();
                    $merchant->commit();
                    $balance_record->commit();
                    echo 'success';die;
                }else{
                    $shop->rollback();
                    $merchant->rollback();
                    $balance_record->rollback();
                    echo 'fail';die;
                }
            }else{
                echo "fail";die;
            }
            //判断该笔订单是否在商户网站中已经做过处理
            //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
            //如果有做过处理，不执行商户的业务程序
            //注意：
            //付款完成后，支付宝系统发送该交易状态通知
        }
        echo 'success';
    }else{
            echo "fail";
      }
    }

    /**
     * 凭证支付成功，回调通知
     */
    public function certificate_notify_url(){
        $arr=$_POST;
        file_put_contents('./Public/log/alipay.log',date('Y-m-d H:i:s').'--'.json_encode($arr),FILE_APPEND);
        $config = C('ALI_CONFIG');
        Vendor('Alipay.pagepay.service.AlipayTradeService');
        $alipaySevice = new \AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST,true));
        $result = $alipaySevice->check($arr);
        if($result) {//验证成功
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $trade_no = $_POST['trade_no'];
            //交易状态
            $trade_status = $_POST['trade_status'];
            $money=$_POST['total_amount'];
            $certificate_db=D('Certificate');
            $certificate_alipay_db=M('certificate_alipay','','XYC');
            if ($trade_status == 'TRADE_SUCCESS') {
                $certificate_alipay_msg=$certificate_alipay_db->WHERE(['orderno'=>$out_trade_no])->FIND();
                $certificate_alipay_db->WHERE(['orderno'=>$out_trade_no])->SAVE(['status'=>'3','real_time'=>time(),'real_money'=>$money]);

                $certificate_db->WHERE(['numbering'=>$certificate_alipay_msg['certificate_no']])->setField('status','1');
            }else{
                $certificate_alipay_db->WHERE(['orderno'=>$out_trade_no])->SAVE(['status'=>'4']);
            }
            echo 'success';
        }else{
            echo "fail";
        }
    }

}